<template>
    <div class="crm-project-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:project:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.projectName" placeholder="请输入项目名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.customerName" placeholder="请输入客户/企业名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入合同名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.projectStatus" placeholder="请选择项目状态" multiple clearable class="w100">
                        <el-option label="未开始" value="0"></el-option>
                        <el-option label="进行中" value="1"></el-option>
                        <el-option label="已完成" value="2"></el-option>
                        <el-option label="已暂停" value="3"></el-option>
                        <el-option label="已终止" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.assignStatus" placeholder="请选择指派状态" multiple clearable class="w100">
                        <el-option label="未指派" value="0"></el-option>
                        <el-option label="部分指派" value="1"></el-option>
                        <el-option label="全部指派" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.memberRole" placeholder="请选择人员类型" class="w100">
                        <el-option label="负责人" value="ADMIN"></el-option>
                        <el-option label="执行人" value="MEMBER"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.memberName" placeholder="请输入负责人或执行人" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.userName" placeholder="请输入所属用户名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.deptName" placeholder="请输入所属部门名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="完成时间" value="finishTime"></el-option>
                        <el-option label="开始时间" value="projectStartTime"></el-option>
                        <el-option label="结束时间" value="projectEndTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-share" type="primary" @click="loadAmountCrmProject">合计</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:project:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmProject()">新增</el-button>
            <!-- <el-button v-auth="'crm:project:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmProject()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:project:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-table ref="tableCrmProjectRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="expand" align="cneter" width="50" show-overflow-tooltip>
                    <template #default="scope">
                        <ProjectProcess :project="scope.row"></ProjectProcess>
                    </template>
                </el-table-column>
                <el-table-column label="项目名称" prop="projectName" width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户/企业" prop="customerName" min-width="200" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.customerName && scope.row.enterpriseName">{{scope.row.enterpriseName}}</span>
                        <span v-if="scope.row.customerName == undefined">{{ scope.row.enterpriseName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合同编号" prop="contractCode" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同名称" prop="contractName" width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="提成金额" prop="quotaAmount" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.quotaAmount}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="项目状态" prop="projectStatus" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.projectStatus == '0'" class="color-info">未开始</span>
                        <span v-else-if="scope.row.projectStatus == '1'" class="color-primary">进行中</span>
                        <span v-else-if="scope.row.projectStatus == '2'" class="color-success">已完成</span>
                        <span v-else-if="scope.row.projectStatus == '3'" class="color-warning">已暂停</span>
                        <span v-else class="color-danger">已终止</span>
                    </template>
                </el-table-column>
                <el-table-column label="指派状态" prop="assignStatus" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.assignStatus == '0'" class="color-info">未指派 {{ scope.row.assignNum }} / {{ scope.row.asignTotal }}</span>
                        <span v-else-if="scope.row.assignStatus == '1'" class="color-warning">部分指派 {{ scope.row.assignNum }} / {{ scope.row.asignTotal }}</span>
                        <span v-else-if="scope.row.assignStatus == '2'" class="color-success">全部指派 {{ scope.row.assignNum }} / {{ scope.row.asignTotal }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" prop="projectStartTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="结束时间" prop="projectEndTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="完成时间" prop="finishTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属用户" prop="userName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:project:info', 'crm:project:edit', 'crm:project:remove', 'crm:project:activing', 'crm:project:paused', 'crm:project:finished', 'crm:project:stopped']">
                    <template #default="scope">
                        <el-button v-auth="'crm:project:info'" type="primary" link @click="onOpenInfoCrmProject(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:project:edit', 'crm:project:remove', 'crm:project:activing', 'crm:project:paused', 'crm:project:finished', 'crm:project:stopped']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:project:edit'" v-show="['0','1','2','3','4'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmProject(scope.row)">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:remove'" v-show="['0','3','4'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:activing'" v-show="['0'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectStatus(scope.row, '1')">启动</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:paused'" v-show="['1'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectStatus(scope.row, '3')">暂停</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:finished'" v-show="['1','3'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectStatus(scope.row, '2')">完成</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:activing'" v-show="['2','3','4'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectStatus(scope.row, '1')">重启</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:stopped'" v-show="['0','1','3'].includes(scope.row.projectStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectStatus(scope.row, '4')">终止</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmProject(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper, slot"
                :total="tableData.total"
            >
                <template #default v-if="quotaAmountShow">
                    <el-text class="ml10 color-warning">总提成金额：{{ quotaAmount }} 元</el-text>
                    <slot></slot>
                </template>
            </el-pagination>
        </el-card>
        <AddCrmProject ref="addCrmProjectRef" @submit="onTableSearch"/>
        <EditCrmProject ref="editCrmProjectRef" @submit="onTableSearch"/>
        <ChangeCrmProject ref="changeCrmProjectRef" @submit="onTableSearch"/>
        <FinishCrmProject ref="finishCrmProjectRef" @submit="onTableSearch"/>
        <InfoCrmProject ref="infoCrmProjectRef"></InfoCrmProject>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmProject from '/@/views/crm/project/addCrmProject.vue';
import EditCrmProject from '/@/views/crm/project/editCrmProject.vue';
import InfoCrmProject from '/@/views/crm/project/infoCrmProject.vue';
import ChangeCrmProject from '/@/views/crm/project/changeCrmProject.vue';
import FinishCrmProject from '/@/views/crm/project/finishCrmProject.vue';
import ProjectProcess from '/@/views/crm/project/process/index.vue';
import { getCrmProjectList, delCrmProject, editCrmProjectStatus, amountCrmProject } from '/@/api/crm/project/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/project',
    components: { AddCrmProject, EditCrmProject, InfoCrmProject, ChangeCrmProject, FinishCrmProject, ProjectProcess },
    setup() {
        const tableCrmProjectRef = ref();
        const addCrmProjectRef = ref();
        const editCrmProjectRef = ref();
        const changeCrmProjectRef = ref();
        const finishCrmProjectRef = ref();
        const infoCrmProjectRef = ref();
        const state = reactive({
            quotaAmountShow: false,
            quotaAmount: 0,
            search:{
                contractCode: undefined,
                contractName: undefined,
                projectName: undefined,
                customerName: undefined,
                projectStatus: [],
                assignStatus: [],
                timefield: 'createTime',
                memberRole: 'ADMIN',
                memberName: undefined,
                userName: undefined,
                deptName: undefined,
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData =  (params) => {
            state.quotaAmountShow = false;
            const search = { ...state.search, ...params };
            const projectStatusStr = search.projectStatus.join(',');
            const assignStatusStr = search.assignStatus.join(',');
            getCrmProjectList({
                ...search,
                projectStatus: projectStatusStr,
                assignStatus: assignStatusStr,
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmProjectRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.projectName = undefined;
            state.search.customerName = undefined;
            state.search.projectStatus = [];
            state.search.assignStatus = [];
            state.search.memberName = undefined;
            state.search.userName = undefined;
            state.search.deptName = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmProject = (row: object) => {
            addCrmProjectRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmProject = (row: object) => {
            row = row || state.tableData.selections[0];
            editCrmProjectRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的项目信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmProject(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条项目信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmProject([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const onOpenInfoCrmProject = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmProjectRef.value.openDialog(row);
        };

        const projectStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '启动',
                '2': '完成',
                '3': '暂停',
                '4': '终止',
            };
            return statusMap[status] || '未知';
        };

        const onOpenCrmProjectStatus = (row: object, status: string) => {
            if(status == '2'){
                finishCrmProjectRef.value.openDialog(row);
            }else{
                ElMessageBox.confirm(`确认【${ projectStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    editCrmProjectStatus({ id: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };

        const onOpenChangeCrmProject = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmProjectRef.value.openDialog(row);
        };

        const loadAmountCrmProject = (params: object) => {
            state.quotaAmountShow = true;
            const search = { ...state.search, ...params };
            const projectStatusStr = search.projectStatus.join(',');
            amountCrmProject({
                ...search,
                projectStatus: projectStatusStr
            }).then((res) => {
                if(res.code === 0){
                    state.quotaAmount = res.data;
                }
            });
        };

        // 页面加载时
        onMounted(() => {
            loadTableData({});
        });
        return {
            tableCrmProjectRef,
            addCrmProjectRef,
            editCrmProjectRef,
            changeCrmProjectRef,
            finishCrmProjectRef,
            infoCrmProjectRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmProject,
            onOpenEditCrmProject,
            onTabelRowsDel,
            onTabelRowDel,
            onOpenInfoCrmProject,
            onOpenCrmProjectStatus,
            onOpenChangeCrmProject,
            loadAmountCrmProject,
            ...toRefs(state),
        };
    },
};
</script>